<template>
  <div class="loginTemp">
    <div v-for="(item, index) in data.inputs" :key="index" class="inputWrap">
      <img :src="require('../assets/img/' + item.icon + '.png')" alt="" />
      <input
        :type="getType(item.icon)"
        class="input"
        :placeholder="item.placeHolder"
        v-model="item.value"
      />
    </div>
    <div v-if="data.func == 'login'" id="loginFree">
      <input type="checkbox" @change="change" /> 七天免登录
    </div>

    <button @click="request">{{ data.btnName }}</button>
    <div class="tip">
      <span v-if="true">{{ this.tip }}</span>
    </div>
  </div>
</template>

<script>
// require( );
import { Request } from "../until/request";
import { Cookie } from "../until/Cookie";
export default {
  props: ["data"],
  name: "loginTemp",

  data() {
    return {
      //提示文字
      tip: "",
      //是否请求成功
      isSuccess: false,
      //模板执行不同功能时 不同keyArr
      keyArr: {
        login: ["username", "password"],
        register: ["username", "password", "name", "phone"]
      }
    };
  },
  computed: {
    type: function(params) {
      return "text";
    }
  },
  mounted() {
    this.currentFunc = this.data.func;
  },
  methods: {
    setCookie(name, value, day) {
      var date = new Date();
      date.setDate(date.getDate() + day);
      console.log(date);
      document.cookie =
        name + "=" + value + ";expires=" + date.toGMTString() + ";path=/";
    },
    //3.正常登录时是否记住密码
    change(e) {
      //记住密码则将用户数据存入cookie
      if (e.target.checked) {
        let cookie = new Cookie();
        let req = new Request();
        //获取valueArr
        let values = req.getValueArr(this.data);
        let keys = this.keyArr[this.data.func];
        values.forEach((item, index, array) => {
          cookie.set(keys[index], item, 7);
        });
      }
    },
    //请求成功回调
    successCallback() {
      //文字提示
      this.isSuccess = true;
      this.tip = this.data.tips.success;

      //定时清除提示文字 关闭弹窗 跳转至/index
      setTimeout(() => {
        this.isSuccess = false;
        this.tip = "";
        if (this.data.func == "login") {
          //1.改变topbar中的状态（改为退出登录）
          this.$emit("passingStatus", true);
          window.location.href = "#/index";
        }
        // }
      }, 600);
    },
    //请求失败回调
    failCallback() {
      this.tip = this.data.tips.fail;
      setTimeout(() => {
        this.tip = "";
        // }
      }, 600);
    },
    //获取input类型
    getType(name) {
      if (name == "password") {
        return "password";
      }
      return "text";
    },
    //2.正常登录
    //请求
    request() {
      let req = new Request();
      //获取valueArr
      let values = req.getValueArr(this.data);
      //根据当前执行功能取出keyArr
      //添加参数
      let formdata = req.addParams(this.keyArr[this.data.func], values);
      //发送请求
      req
        .send("post", `/api/api/${this.data.func}`, formdata)
        .then(res => {
          if (res.data.code == 200) {
            //当前执行登录功能时
            if (this.data.func == "login") {
              let cookie = new Cookie();
              cookie.set("login", true, 7);
              //储存用户信息 方便其他组件使用

              console.log(res.data.data);
              sessionStorage.setItem("userId", res.data.data.id);
              sessionStorage.setItem("username", formdata.get("username"));
              sessionStorage.setItem("password", formdata.get("password"));
              //2.改变myDouban中的状态（isLogin:true）
              sessionStorage.setItem("login", true);
            }
            this.successCallback();
          } else {
            this.failCallback();
          }
        })
        .catch(err => {
          console.log(err);
          this.failCallback();
        });
      //   console.log()
    }
  }
};
</script>

<style scoped>
.loginTemp {
  padding-top: 0.3rem;
  display: flex;
  flex-direction: column;
}
.inputWrap {
  display: flex;
  justify-content: center;
  position: relative;
}

.inputWrap img {
  width: 1rem;
  height: 1rem;
  position: absolute;
  left: 5.5rem;
  top: 1.5rem;
}
.inputWrap .input {
  width: 18rem;
  height: 2rem;
  margin: 1rem 0;
  padding-left: 2rem;
  border: 1px solid #bfbfbf;
  border-radius: 2px;
}
#loginFree {
  width: 20rem;
  height: 1.5rem;
  margin: 0.5rem auto 0;
  /* background: #ccc; */
}
button {
  width: 20rem;
  height: 2rem;
  margin: 1.2rem auto 0;
  border-radius: 0.2rem;
  color: white;
  font-size: 1rem;
  background: #1a8cff;
  cursor: pointer;
}
button:hover {
  background: #0066cc;
}
.tip {
  width: 20rem;
  height: 3rem;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  font: 1.5rem bold;
  color: #0066cc;
}
</style>